<template>
  <div class="basic_info">
    <div class="info_operation_btn">
      <div class="btn_left">
        <el-button type="primary" @click="getDataList">统计</el-button>
        <el-button @click="exportExcel">导出</el-button>
        <el-button @click="handleShortcutKeyPrint">打印(P)</el-button>
      </div>
      <div class="btn_right">
        <el-select @change="changeDate" v-model="monthValue">
          <el-option
            v-for="item in monthOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-date-picker
          v-model="nowDate"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="onClickPicker"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <i @click="onShowColumn()" class="set_up el-icon-s-tools"></i>
      </div>
    </div>
    <div class="info_content_div">
      <div class="div_table">
        <div class="table_content">
          <el-table
            ref="tableRef"
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            :header-cell-style="{
            background: '#E3F6FF',
            color: '#666666',
            textAlign: 'center',
            height: '30px',
            borderColor: '#dddddd',
          }"
            :cell-style="{ textAlign: 'center' }"
            :data="tableData"
            height="100%"
            style="width: 100%"
          >
            <el-table-column :label="item.label" v-for="(item, index) in columnData" :key="index">
              <el-table-column
                :show-overflow-tooltip="true"
                v-for="(v, i) in item.subset"
                :key="i"
                :prop="v.props"
                :label="v.morenName"
                min-width="120px"
                :width="v.props == 'xh' ? '50px' : v.props == 'staticDate' ? '200px' : ''"
              >
                <template slot-scope="scope">
                  <span v-if="arr.includes(v.props)">{{ $formatMoney(scope.row[v.props]) }}</span>
                  <span v-else>{{ scope.row[v.props] }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <div class="table_pagination">
          <div class="pagination_div">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="pagesize"
              layout="jumper, prev, pager,next, sizes"
              :total="tableData.length"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 列配置弹框 -->
    <CConfiguration
      ref="setColumnRef"
      :columnDataArr="[]"
      :defaultColumnDataArr="[]"
      orderType="经营状态报表"
      @onSaveColumn="onSaveColumn"
    ></CConfiguration>
    <!-- 打印 -->
    <dialog-print ref="print"></dialog-print>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import CConfiguration from '@/components/c_column/columnConfiguration1'
/**打印 */
import dialogPrint from '@/views/components/dialogPrintStatic'
import { dateStrFromDate } from '@/utils/DateFormatter'
import { postAction } from '../../../api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { handlePermissions, handleOtherPerms } from '@/utils/index'
import { delcommafy, formatMoney } from '../../../utils'
export default {
  name: 'operatingStatement',
  components: {
    CConfiguration,
    dialogPrint,
  },
  mixins: [JeecgListMixin],
  computed: {
    ...mapGetters(['name']),
    buttonsPermissions () {
      return handlePermissions(this.api)
    },
    printPermissions () {
      return handleOtherPerms('单据可多次打印')
    },
  },
  created () {
    // 默认获取当月时间
    this.getTimeRange(this.$setTimeRange(5))
    this.getData()
  },
  data () {
    return {
      // 查询条件数据
      queryData: {
        startDate: '',
        endDate: '',
      },
      // 时间区间选择
      monthValue: '本月',
      monthOptions: [
        {
          value: '今日',
          label: '今日',
        },
        {
          value: '本周',
          label: '本周',
        },
        {
          value: '本月',
          label: '本月',
        },
        {
          value: '本年',
          label: '本年',
        },
      ],
      isShowDate: true, // 是否显示选择时间组件
      nowDate: [],
      // 表格数据
      tableData: [],
      columnData: [
        {
          props: 'rq',
          label: '日期',
          subset: [
            {
              id: '1',
              morenName: '序号',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 0,
              zidingyiSort: 0,
              noModify: true,
              props: 'xh',
            },
            {
              id: '2',
              morenName: '统计日期',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 1,
              zidingyiSort: 1,
              noModify: true,
              props: 'staticDate',
            },
          ],
        },
        {
          props: 'sr',
          label: '收入',
          subset: [
            {
              id: '1',
              morenName: '销售收入',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 0,
              zidingyiSort: 0,
              noModify: true,
              props: 'salesRevenue',
            },
          ],
        },
        {
          props: 'zc',
          label: '支出',
          subset: [
            {
              id: '1',
              morenName: '销售成本',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 0,
              zidingyiSort: 0,
              noModify: true,
              props: 'salesCost',
            },
          ],
        },
        {
          props: 'sfk',
          label: '收付款',
          subset: [
            {
              id: '1',
              morenName: '收款金额',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 0,
              zidingyiSort: 0,
              noModify: true,
              props: 'settlementAmount',
            },
            {
              id: '2',
              morenName: '付款金额',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 1,
              zidingyiSort: 1,
              noModify: true,
              props: 'paymentAmount',
            },
          ],
        },
        {
          props: 'jylr',
          label: '经营利润',
          subset: [
            {
              id: '1',
              morenName: '销售毛利',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 0,
              zidingyiSort: 0,
              noModify: true,
              props: 'salesGrossProfit',
            },
            {
              id: '2',
              morenName: '毛利率',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              morenSort: 1,
              zidingyiSort: 1,
              noModify: true,
              props: 'grossProfitMargin',
            },
          ],
        },
      ],
      pagesize: 20, //每页的数据条数
      currentPage: 1, //默认开始页面
      api: '经营状况报表',
      url: {
        exportXlsUrl: '/financialstatements/operatingstatements/exportXls'
      },
      arr: ['salesRevenue', 'salesCost', 'settlementAmount', 'paymentAmount', 'salesGrossProfit'],
      arr1: ['salesRevenue', 'salesCost', 'settlementAmount', 'paymentAmount', 'salesGrossProfit'],
      printClick: false,
    }
  },
  methods: {
    // 打印
    handleShortcutKeyPrint () {
      this.printClick = true
      this.getDataList()
    },
    handlePrint () {
      // if (!this.buttonsPermissions.DaYin) {
      //   this.$elMessage.warning('未拥有打印权限！')
      // } else 
      if (!this.tableData || this.tableData.length <= 0) {
        this.$elMessage.warning('没有要打印的记录！')
      } else {
        let printData = {
          riqi: this.queryData.startDate + '~' + this.queryData.endDate,
          printExclusive: this.tableData.map((item) => {
            item.salesRevenue = formatMoney(item.salesRevenue)
            item.salesCost = formatMoney(item.salesCost)
            item.settlementAmount = formatMoney(item.settlementAmount)
            item.paymentAmount = formatMoney(item.paymentAmount)
            item.salesGrossProfit = formatMoney(item.salesGrossProfit)
            return item
          }),
        }
        // 可以多次打印设置
        if (this.printPermissions) {
          this.$refs.print.show(printData, this.columnData, this.api)
        } else {
          if (this.$lcStorage.get('printLimitValue')) {
            // 获取打印次数
            this.getPrintNum(this.api, (() => {
              this.$refs.print.show(printData, this.columnData, this.api)
            }))
          } else {
            this.$refs.print.show(printData, this.columnData, this.api)
          }
        }
      }
    },
    // 获取数据
    getData () {
      this.selectTitle()
      this.getDataList()
    },
    // 初始化查询列配置值
    async selectTitle () {
      let obj = await this.$setColumn.selectColumn(this.api)
      if (obj.code === 200) {
        this.updateId = obj.updateId
        this.columnData = JSON.parse(JSON.stringify(obj.columnData))
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.api, this.columnData)
        this.updateId = id
      }
      console.log(this.columnData);
    },
    // 触发列配置弹框
    onShowColumn () {

      let list = []
      for (let index = 0; index < this.columnData.length; index++) {
        const element = this.columnData[index];
        let sub = element.subset
        list = list.concat(sub)
      }
      let defaultColumnData = JSON.parse(JSON.stringify(this.$options.data().columnData))
      let defaultList = []
      for (let index = 0; index < defaultColumnData.length; index++) {
        const element = defaultColumnData[index];
        let sub = element.subset
        defaultList = defaultList.concat(sub)
      }
      this.$refs.setColumnRef.loadData(list, defaultList)

    },
    // 列配置修改后数据获取
    async onSaveColumn (value) {
      let nIndex = 0
      console.log(this.columnData);
      this.columnData.forEach((lItem, lIndex) => {
        let subList = lItem.subset
        if (lIndex > 0) {
          nIndex += this.columnData[lIndex - 1].subset.length
        }
        let list = []
        let count = 0 //记录隐藏的个数
        subList.forEach((item, index) => {
          let nItem = value[nIndex + index]
          list.push(nItem)
          if (!nItem.zidingyiState) {
            count++
          }
        })
        lItem.subset = list
        lItem.show = !(count == list.length)
        this.columnData.splice(lIndex, 1, lItem)
      })
      let res = await this.$setColumn.editColumn(this.api, this.columnData, this.updateId)
      if (res.code == 200) {
        this.$elMessage.success(res.message)
      } else {
        this.$elMessage.error(res.message)
      }
    },
    getDataList () {
      // let parmas = {
      //   ...this.queryData,
      // }
      postAction('/financialstatements/operatingstatements/count', this.queryData).then(res => {
        console.log(res);
        if (res.success) {
          let item = res.result
          if (item) {
            item.xh = 1
            item.staticDate = this.monthValue == '全部' ? '全部' : `${this.queryData.startDate}至${this.queryData.endDate}`
            item.grossProfitMargin = item.grossProfitMargin + '%'
            this.tableData = [item]
            this.$nextTick(() => {
              this.$refs.tableRef.doLayout()
            })
          }
        } else {
          this.$elMessage.error(res.message)
        }
        if (this.printClick) {
          this.handlePrint()
        }
        this.printClick = false
      })
    },
    // 判断当前选择时间段
    changeDate (val) {
      this.isShowDate = true
      switch (val) {
        case '全部':
          this.getTimeRange({
            now: '',
            end: ''
          })
          break
        case '今日':
          this.getTimeRange(this.$setTimeRange(1))
          break
        case '昨天':
          this.getTimeRange(this.$setTimeRange(2))
          break
        case '本周':
          this.getTimeRange(this.$setTimeRange(3))
          break
        case '上周':
          this.getTimeRange(this.$setTimeRange(4))
          break
        case '本月':
          this.getTimeRange(this.$setTimeRange(5))
          break
        case '上月':
          this.getTimeRange(this.$setTimeRange(6))
          break
        case '本年':
          this.getTimeRange(this.$setTimeRange(7))
          break
        case '去年':
          this.getTimeRange(this.$setTimeRange(8))
          break
        default:
          break
      }
    },
    // 获取时间范围并设置
    getTimeRange (data) {
      this.nowDate = [data.now, data.end]
      this.queryData.startDate = data.now
      this.queryData.endDate = data.end
    },
    // 获取当前选中时间
    onClickPicker (val) {
      this.queryData.startDate = val[0]
      this.queryData.endDate = val[1]
    },
    // 合计列计算
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      console.log(data);
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.tableData.length + '条明细'
        } else if (this.arr1.includes(column.property)) {
          let item = data[0]
          if (item) {
            if (this.arr.includes(column.property)) {
              sums[index] = this.$formatMoney(delcommafy(item[column.property]))
            } else {
              sums[index] = item[column.property]
            }
          } else {
            sums[index] = ''
          }

        }
      })
      return sums
    },

    // 设置列配置（实现列的显示隐藏、列名修改、还原默认值；上下移动列未实现）
    setColumn () {
      let getTable = document.getElementsByClassName('table_content')[0]
      let getTr = getTable.getElementsByTagName('tr')
      getTr.forEach((item) => {
        let getTd = item.getElementsByClassName('set_order')
        getTd.forEach((item, index) => {
          // item.style.order = this.newColumnData[index].zidingyiSort
          if (this.newColumnData[index].zidingyiState == false) {
            item.style.display = 'none'
          } else {
            item.style.display = 'block'
          }
        })
      })
      let getTh = getTr[0].getElementsByClassName('set_order')
      getTh.forEach((item, index) => {
        // item.style.order = this.newColumnData[index].zidingyiSort
        if (this.newColumnData[index].zidingyiState == false) {
          item.style.display = 'none'
        } else {
          item.style.display = 'block'
        }
      })
    },
    // 获取每页几条数据
    handleSizeChange (val) {
      this.pagesize = val
    },
    // 获取当前第几页
    handleCurrentChange (val) {
      this.currentPage = val
    },
    exportExcel () {
      let queryParam = {
        ...this.queryData,
        fileName: '经营状况报表',
      }
      this.handleExportXlsByStaff('经营状况报表', queryParam)
    }
  },
}
</script>

<style lang="scss" scoped>
.basic_info {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.info_operation_btn {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  ::v-deep .el-button {
    width: 70px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-right: 10px;
    margin-left: 0;
    border-radius: 0.1rem;
    border: none;
  }

  .el-button--default {
    color: #666;
    border: none;
  }

  .el-button--default:hover {
    background-color: #ffffff;
  }

  ::v-deep .el-select {
    width: 80px;
    height: 30px;
    box-sizing: border-box;
    margin-right: 0.112507rem;

    .el-input {
      .el-input__inner {
        height: 30px;
        border: none;
        font-size: 12px;
      }

      .el-input__suffix {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
  }

  ::v-deep .el-date-editor {
    width: 220px;
    height: 30px;
    background: #ffffff;
    border: 1px solid #d9d9d9;
    margin-right: 0.112507rem;
    padding: 3px 6px;

    .el-range__icon {
      position: absolute;
      right: 0;
      line-height: 30px;
    }

    .el-range-separator {
      line-height: 24px;
    }

    .el-range-input {
      font-size: 12px;
    }

    .el-range__close-icon {
      display: none;
    }
  }

  .btn_left {
    width: 60%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .btn_right {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .set_up {
      font-size: 20px;
      color: rgb(153, 153, 153);
    }
  }
}

.info_content_div {
  width: 100%;
  height: calc(100% - 60px);
  margin-top: 10px;
  background-color: #ffffff;
  padding: 10px;

  .div_table {
    width: 100%;
    height: 100%;

    .table_content {
      height: calc(100% - 50px);

      ::v-deep .el-table {
        border-color: #ddd;
        box-sizing: border-box;

        th,
        td {
          padding: 0;
          color: #666;
        }

        .el-table__header {
          tr {
            &:last-child {
              th {
                background: rgb(237, 237, 237) !important;
              }
            }
          }
        }

        .cell {
          line-height: 30px;
          font-size: 12px;
          text-align: center;
        }

        .el-table__body tr:hover > td {
          background: #e3f6ff;
        }

        .el-table__footer-wrapper {
          td {
            background: #f4f4f4;
            border: none;
          }
        }

        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 10px;
          background-color: #e5e5e5;
        }

        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          background-color: #c9c9c9;
        }
      }
    }

    .table_pagination {
      width: 100%;
      height: 50px;
      box-sizing: border-box;
      padding: 10px 0;
      display: flex;

      .pagination_div {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        ::v-deep .el-pagination {
          padding: 0;
          height: 30px;

          .el-pagination__sizes {
            margin: 0;

            .el-input {
              margin-right: 0;
            }
          }
        }
      }
    }
  }
}
</style>